<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="店铺id" prop="sid">
              <el-input v-model="queryParams.sid" placeholder="请输入店铺id" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="国家" prop="marketplace">
              <el-input v-model="queryParams.marketplace" placeholder="请输入国家" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="MSKU" prop="sellerSku">
              <el-input v-model="queryParams.sellerSku" placeholder="请输入MSKU" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="FNSKU" prop="fnsku">
              <el-input v-model="queryParams.fnsku" placeholder="请输入FNSKU" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="ASIN" prop="asin">
              <el-input v-model="queryParams.asin" placeholder="请输入ASIN" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="父ASIN" prop="parentAsin">
              <el-input v-model="queryParams.parentAsin" placeholder="请输入父ASIN" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="本地产品SKU" prop="localSku">
              <el-input v-model="queryParams.localSku" placeholder="请输入本地产品SKU" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="品名" prop="localName">
              <el-input v-model="queryParams.localName" placeholder="请输入品名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleSyncData">同步数据</el-button>
          </el-col>
          <el-col :span="15">
            数据更新时间：
            <el-text>{{ newestUpdateTime }}</el-text>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="amazonListingList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="主键" align="center" prop="id" />
        <el-table-column label="国家" align="center" prop="marketplace" />
        <el-table-column label="MSKU" align="center" prop="sellerSku" width="250" />
        <el-table-column label="ASIN" align="center" prop="asin" width="120" />
        <el-table-column label="父ASIN" align="center" prop="parentAsin" width="120" />
        <el-table-column label="状态：0 停售，1 在售" align="center" prop="status" />
        <el-table-column label="是否删除：0 否，1 是" align="center" prop="isDelete" />
        <el-table-column label="标题" align="center" prop="itemName" show-overflow-tooltip />
        <el-table-column label="本地产品SKU" align="center" prop="localSku" width="250" />
        <el-table-column label="品名" align="center" prop="localName" width="250" />
        <el-table-column label="运营负责人ID" align="center" prop="operaUserId" width="250" />
        <el-table-column label="运营负责人名称" align="center" prop="operaUserName" width="250" />

        <!-- <el-table-column label="价格【不包含促销，运费，积分】" align="center" prop="price" />
        <el-table-column label="FBA可售" align="center" prop="afnFulfillableQuantity" />
        <el-table-column label="FBA不可售" align="center" prop="afnUnsellableQuantity" />
        <el-table-column label="待调仓" align="center" prop="reservedFcTransfers" />
        <el-table-column label="调仓中" align="center" prop="reservedFcProcessing" />
        <el-table-column label="待发货" align="center" prop="reservedCustomerorders" />
        <el-table-column label="在途" align="center" prop="afnInboundShippedQuantity" />
        <el-table-column label="计划入库" align="center" prop="afnInboundWorkingQuantity" />
        <el-table-column label="入库中" align="center" prop="afnInboundReceivingQuantity" /> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['lingxing:amazonListing:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                v-hasPermi="['lingxing:amazonListing:remove']"
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改亚马逊链接对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="amazonListingFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="亚马逊定义的listing的id【可能为空】" prop="listingId">
          <el-input v-model="form.listingId" placeholder="请输入亚马逊定义的listing的id【可能为空】" />
        </el-form-item>
        <el-form-item label="店铺id" prop="sid">
          <el-input v-model="form.sid" placeholder="请输入店铺id" />
        </el-form-item>
        <el-form-item label="国家" prop="marketplace">
          <el-input v-model="form.marketplace" placeholder="请输入国家" />
        </el-form-item>
        <el-form-item label="MSKU" prop="sellerSku">
          <el-input v-model="form.sellerSku" placeholder="请输入MSKU" />
        </el-form-item>
        <el-form-item label="FNSKU" prop="fnsku">
          <el-input v-model="form.fnsku" placeholder="请输入FNSKU" />
        </el-form-item>
        <el-form-item label="ASIN" prop="asin">
          <el-input v-model="form.asin" placeholder="请输入ASIN" />
        </el-form-item>
        <el-form-item label="父ASIN" prop="parentAsin">
          <el-input v-model="form.parentAsin" placeholder="请输入父ASIN" />
        </el-form-item>
        <el-form-item label="商品缩略图地址" prop="smallImageUrl">
          <el-input v-model="form.smallImageUrl" placeholder="请输入商品缩略图地址" />
        </el-form-item>
        <el-form-item label="是否删除：0 否，1 是" prop="isDelete">
          <el-input v-model="form.isDelete" placeholder="请输入是否删除：0 否，1 是" />
        </el-form-item>
        <el-form-item label="标题" prop="itemName">
          <el-input v-model="form.itemName" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="本地产品SKU" prop="localSku">
          <el-input v-model="form.localSku" placeholder="请输入本地产品SKU" />
        </el-form-item>
        <el-form-item label="品名" prop="localName">
          <el-input v-model="form.localName" placeholder="请输入品名" />
        </el-form-item>
        <el-form-item label="币种" prop="currencyCode">
          <el-input v-model="form.currencyCode" placeholder="请输入币种" />
        </el-form-item>
        <el-form-item label="价格【不包含促销，运费，积分】" prop="price">
          <el-input v-model="form.price" placeholder="请输入价格【不包含促销，运费，积分】" />
        </el-form-item>
        <el-form-item label="总价【包含了促销、运费、积分】" prop="landedPrice">
          <el-input v-model="form.landedPrice" placeholder="请输入总价【包含了促销、运费、积分】" />
        </el-form-item>
        <el-form-item label="优惠价" prop="listingPrice">
          <el-input v-model="form.listingPrice" placeholder="请输入优惠价" />
        </el-form-item>
        <el-form-item label="运费" prop="shipping">
          <el-input v-model="form.shipping" placeholder="请输入运费" />
        </el-form-item>
        <el-form-item label="积分，日本站才有" prop="points">
          <el-input v-model="form.points" placeholder="请输入积分，日本站才有" />
        </el-form-item>
        <el-form-item label="FBM库存" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入FBM库存" />
        </el-form-item>
        <el-form-item label="FBA可售" prop="afnFulfillableQuantity">
          <el-input v-model="form.afnFulfillableQuantity" placeholder="请输入FBA可售" />
        </el-form-item>
        <el-form-item label="FBA不可售" prop="afnUnsellableQuantity">
          <el-input v-model="form.afnUnsellableQuantity" placeholder="请输入FBA不可售" />
        </el-form-item>
        <el-form-item label="待调仓" prop="reservedFcTransfers">
          <el-input v-model="form.reservedFcTransfers" placeholder="请输入待调仓" />
        </el-form-item>
        <el-form-item label="调仓中" prop="reservedFcProcessing">
          <el-input v-model="form.reservedFcProcessing" placeholder="请输入调仓中" />
        </el-form-item>
        <el-form-item label="待发货" prop="reservedCustomerorders">
          <el-input v-model="form.reservedCustomerorders" placeholder="请输入待发货" />
        </el-form-item>
        <el-form-item label="在途" prop="afnInboundShippedQuantity">
          <el-input v-model="form.afnInboundShippedQuantity" placeholder="请输入在途" />
        </el-form-item>
        <el-form-item label="计划入库" prop="afnInboundWorkingQuantity">
          <el-input v-model="form.afnInboundWorkingQuantity" placeholder="请输入计划入库" />
        </el-form-item>
        <el-form-item label="入库中" prop="afnInboundReceivingQuantity">
          <el-input v-model="form.afnInboundReceivingQuantity" placeholder="请输入入库中" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AmazonListing" lang="ts">
import {
  listAmazonListing,
  getAmazonListing,
  delAmazonListing,
  addAmazonListing,
  updateAmazonListing,
  syncData,
  getNewestUpdateTime
} from '@/api/lingxing/amazonListing';
import { AmazonListingVO, AmazonListingQuery, AmazonListingForm } from '@/api/lingxing/amazonListing/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const amazonListingList = ref<AmazonListingVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const amazonListingFormRef = ref<ElFormInstance>();
const newestUpdateTime = ref('');

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: AmazonListingForm = {
  id: undefined,
  listingId: undefined,
  sid: undefined,
  marketplace: undefined,
  sellerSku: undefined,
  fnsku: undefined,
  asin: undefined,
  parentAsin: undefined,
  smallImageUrl: undefined,
  status: undefined,
  isDelete: undefined,
  itemName: undefined,
  localSku: undefined,
  localName: undefined,
  currencyCode: undefined,
  price: undefined,
  landedPrice: undefined,
  listingPrice: undefined,
  shipping: undefined,
  points: undefined,
  quantity: undefined,
  afnFulfillableQuantity: undefined,
  afnUnsellableQuantity: undefined,
  reservedFcTransfers: undefined,
  reservedFcProcessing: undefined,
  reservedCustomerorders: undefined,
  afnInboundShippedQuantity: undefined,
  afnInboundWorkingQuantity: undefined,
  afnInboundReceivingQuantity: undefined
};
const data = reactive<PageData<AmazonListingForm, AmazonListingQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    listingId: undefined,
    sid: undefined,
    marketplace: undefined,
    sellerSku: undefined,
    fnsku: undefined,
    asin: undefined,
    parentAsin: undefined,
    smallImageUrl: undefined,
    status: undefined,
    isDelete: undefined,
    itemName: undefined,
    localSku: undefined,
    localName: undefined,
    currencyCode: undefined,
    price: undefined,
    landedPrice: undefined,
    listingPrice: undefined,
    shipping: undefined,
    points: undefined,
    quantity: undefined,
    afnFulfillableQuantity: undefined,
    afnUnsellableQuantity: undefined,
    reservedFcTransfers: undefined,
    reservedFcProcessing: undefined,
    reservedCustomerorders: undefined,
    afnInboundShippedQuantity: undefined,
    afnInboundWorkingQuantity: undefined,
    afnInboundReceivingQuantity: undefined,
    params: {}
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);

/** 查询亚马逊链接列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAmazonListing(queryParams.value);
  amazonListingList.value = res.rows;
  total.value = res.total;
  loading.value = false;

  const res1 = await getNewestUpdateTime();
  newestUpdateTime.value = res1.msg;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  amazonListingFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: AmazonListingVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加亚马逊链接';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: AmazonListingVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getAmazonListing(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改亚马逊链接';
};

/** 提交按钮 */
const submitForm = () => {
  amazonListingFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateAmazonListing(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addAmazonListing(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: AmazonListingVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除亚马逊链接编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delAmazonListing(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'oa/amazonListing/export',
    {
      ...queryParams.value
    },
    `amazonListing_${new Date().getTime()}.xlsx`
  );
};

/** 同步数据按钮操作 */
const handleSyncData = async (row?: AmazonListingVO) => {
  loading.value = true;
  await proxy?.$modal.confirm('是否同步领星数据项？').finally(() => (loading.value = false));
  loading.value = true;
  await syncData().finally(() => (loading.value = false));
  proxy?.$modal.msgSuccess('同步数据成功!');
  loading.value = true;
  await getList().finally(() => (loading.value = false));
};

onMounted(() => {
  getList();
});
</script>
